<template>
  <div class="sys-avatar">
    <img v-if="!isMiniprogram" class="sys-avatar-image" :class="avatarClassName" :src="url">
    <img v-else-if="imgMode!==''" class="sys-avatar-image" :class="avatarClassName" :style="imgStyle" :src="url" :mode="imgMode">
  </div>
</template>

<script>
  export default {
    props: {
      url: {
        type: String,
        required: true
      },
      shape: {
        type: String,
        default: ''
      }
    },

    computed: {
      avatarClassName() {
        let shape = this.shape;
        if (shape === '') {
          return '';
        }
        return 'sys-avatar-' + shape;
      },

      imgStyle() {
        let imgMode = this.imgMode;
        if (imgMode === 'heightFix') {
          return {
            height: '100%'
          };
        } else if (imgMode === 'widthFix') {
          return {
            width: '100%'
          };
        }
        return {};
      }
    },

    data() {
      return {
        isMiniprogram: process.env.isMiniprogram,
        imgMode: ''
      };
    },

    created() {
      if (!this.isMiniprogram) {
        return;
      }

      let shape = this.shape;
      if (shape === 'square') {
        this.imgMode = 'widthFix';
        // wx.getImageInfo({
        //   src: this.url,
        //   success: res => {
        //     let width = res.width;
        //     let height = res.height;
        //     if (width >= height) {
        //       this.imgMode = 'widthFix';
        //     } else {
        //       this.imgMode = 'heightFix';
        //     }
        //   }
        // });
      } else {
        this.imgMode = 'aspectFit';
      }
    }
  };

</script>

<style lang="scss">
  .sys-avatar {
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: relative;

    .sys-avatar-image {
      display: block;

      &.sys-avatar-circle {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        object-fit: scale-down;
      }

      @if $isMini {
        &.sys-avatar-square {
          @extend .center-middle;
          border-radius: formatPx(8);
        }
      }

      @else {
        &.sys-avatar-square {
          @extend .center-middle;
          max-height: 100%;
          max-width: 100%;
          border-radius: formatPx(8);
        }
      }
    }
  }

</style>
